package com.edu.hre.struts.action.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.cache.PassiveDynaCache;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreSubunit;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.admin.StructureForm;

public class StructureAction extends DispatchAction {
	
	private static final Logger logger = Logger.getLogger(StructureAction.class);
	private static final PassiveDynaCache passiveDynaCache = BeanFinder.getBean(PassiveDynaCache.BEAN_NAME, PassiveDynaCache.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "structure";
	private static final String hrefDelete = "<a title=\"Delete unit\" style=\"text-decoration:none;color:blue;\" href=\"javascript:confirmHref('btnDelete=clicked&id=@id','Are you sure you want to delete the selected items?');\">&nbsp;&nbsp;[-]</a>";
	private static final String hrefAdd = "<a title=\"Add unit\" style=\"text-decoration:none;color:blue;\" href=\"javascript:openPopup('structureUpdate.do?act=add&level=@level&id=@id','Add Sub Unit for @unitName','460px','200px');\">&nbsp;&nbsp;[+]</a>"; 
	private static final String hrefEdit = "<a title=\"Edit unit\" style=\"text-decoration:none;color:blue;\" href=\"javascript:openPopup('structureUpdate.do?act=edit&id=@id','Edit unit @unitName','460px','200px');\">&nbsp;&nbsp;[*]</a>";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		StructureForm beanForm = (StructureForm) form;
		if(request.getParameter(StringConstants.BTN_DELETE) != null){
			String id = request.getParameter("id");
			passiveDynaCache.removeCachedItem(RequestUtils.Attribute.LIST_SUB_UNITS_STRUCTURE);
			deleteItem(Integer.parseInt(id));
		}
		HreSubunit tmp = new HreSubunit();
		tmp.setId(0);
		StringBuilder html = new StringBuilder();
		buildHtml(tmp, html);
		String htmlTree = html.toString().replaceFirst("<ul", "<ul id=\"red\" class=\"treeview-red\"");
		beanForm.setHtmlTree(htmlTree);
		return mapping.findForward(ACTION_NAME);
	}
	 
	private void buildHtml(HreSubunit obj, StringBuilder html){
		List<HreSubunit> listChild = baseService.getPojos("parentId", Compare.EQUAL, obj.getId(), null, null, 0, 0, HreSubunit.class);
		if(listChild == null || listChild.size() == 0){
			return;
		}
		html.append("<ul>\n");
		for(int i = 0; i < listChild.size(); i++){
			HreSubunit tmp = (HreSubunit) listChild.get(i);
			html.append("<li>" + tmp.getName());
			html.append(hrefEdit.replace("@unitName", tmp.getName().toUpperCase()).replace("@id", String.valueOf(tmp.getId())));
			if(tmp.getParentId() != 0 && tmp.getLevel() != 1){
				html.append(hrefDelete.replace("@id", String.valueOf(tmp.getId())));
			}
			html.append(hrefAdd.replace("@level", tmp.getLevel() + "").replace("@unitName", tmp.getName().toUpperCase()).replace("@id", String.valueOf(tmp.getId())));
			buildHtml(tmp, html);
			html.append("</li>\n");
		}
		html.append("</ul>\n");
	}
	
	private void deleteItem(Integer id){
		List<HreSubunit> list = baseService.getPojos("parentId", Compare.EQUAL, id, null, null, 0, 0, HreSubunit.class);
		for(int i = 0; list != null && i < list.size(); i ++){
			HreSubunit tmp = (HreSubunit) list.get(i);
			deleteItem(tmp.getId());
		}
		HreSubunit tmp = baseService.getPojo(id, HreSubunit.class);
		if(tmp.getParentId() != 0 && tmp.getLevel() != 1){
			baseService.deletePojo(tmp);
		}
	}
}
